package com.luojing.springbootsecurity.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

/**
 * 此类继承WebSecurityConfigurerAdapter,WebSecurityConfigurerAdapter默认为spring security的一个默认登录页面配置,如果需要自定义登录页面,只需要继承并重写configur 方法即可
 * 参考spring-security官方文档:
 * You might be wondering where the login form came from when you were prompted to log in,
 * since we made no mention of any HTML files or JSPs.
 * Since Spring Security’s default configuration does not explicitly set a URL for the login page,
 * Spring Security generates one automatically,
 * based on the features that are enabled and using standard values for the URL which processes the submitted login,
 * the default target URL the user will be sent to after logging in and so on.
 *
 * While the automatically generated log in page is convenient to get up and running quickly,
 * most applications will want to provide their own log in page. To do so we can update our configuration as seen below
 * @author luojing
 * @create 2018/10/16 10:24 AM
 **/
@EnableWebSecurity
public class WebSecurityConfigurerConfig extends WebSecurityConfigurerAdapter {
  @Autowired
  private LogoutHandlerConfig logoutHandlerConfig;

  @Autowired
  private LogoutSuccessHandlerConfig logoutSuccessHandlerConfig;

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests().antMatchers("/resources/**","/js/**").permitAll()
        //指定访问路径需要给定的角色
        .antMatchers("/admin/**").hasRole("ADMIN")
        .anyRequest().authenticated()
        .and()
        .formLogin()
        // 关键在这里重新定义了登录页的地址
        .loginPage("/login")
        //登录表单指定的提交地址
        .loginProcessingUrl("/user/login")
        .permitAll().and()
        .logout()
        .deleteCookies("a")
        .addLogoutHandler(logoutHandlerConfig)
        .logoutSuccessHandler(logoutSuccessHandlerConfig)
        .logoutSuccessUrl("http://www.baidu.com")
        .and().csrf().disable();
  }
}
